package com.qfjy.controller;

import com.alibaba.fastjson2.JSON;
import com.qfjy.entity.po.User;
import com.qfjy.entity.utils.ExcelUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("excel")
public class ExcelController {
    /**
     * 导出功能
     */
    @RequestMapping("export")  //excel/export
    public String exportExcel(HttpServletResponse response) throws IOException {

        List<User> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            User u = new User();
            u.setId(i + 1);
            u.setName("哈哈" + i);
            u.setStatus((short) 1);
            list.add(u);
        }
        ExcelUtils.exportExcel(list, "用户信息列表", "用户信息", User.class, "用户信息文件", response);
        return "";
    }

    /**
     * 导入功能
     */
    @RequestMapping("upload")   // excel/upload
//    @ResponseBody
    public String uploadExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        long startTime = System.currentTimeMillis();
        try {
            List<User> list = ExcelUtils.importExcel(file, User.class);
//            System.out.println(list.toString());
//
//            System.out.println("------>打印------>");
//            for (int i = 0; i < list.size(); i++) {
//                System.out.println(list.get(i));
//            }

//            HttpSession session = request.getSession();
//            session.setAttribute("userList", list);

            Object userList = JSON.toJSON(list);
            request.setAttribute("userList",userList);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        long endTime = System.currentTimeMillis();
//        System.out.println("用时：" + (endTime - startTime));
        return "forward:/user/insertBatchUsers";
    }
}
